<?php

namespace app\model;

use think\Model;

//产品表
class Products extends Model
{
    // Define the table name
    protected $name = 'products';
    public $timestamps = false;

    // 产品属性
    public function attributes()
    {
        return $this->hasMany(ProductAttributes::class,  'product_id','id');
    }

    // 产品分类
    public function categories()
    {
        return $this->hasMany(ProductCategories::class,  'product_id','id');
    }

    // 产品详情
    public function description()
    {
        // locale
        return $this->hasOne(ProductDescriptions::class,  'product_id','id')->where('locale', 'zh_cn');
    }

    // 产品SKU
    public function skus()
    {
        return $this->hasMany(ProductSkus::class,  'product_id','id');
    }

    // 获取默认sku
    public function defaultSku()
    {
        return $this->hasOne(ProductSkus::class,  'product_id','id')->where('is_default', 1);
    }

    // 商户
    public function seller()
    {
        return $this->hasOne(Sellers::class,  'id','seller_id');
    }

    // 品牌
    public function brand()
    {
        return $this->hasOne(ProductBrands::class,  'id','brand_id');
    }

    public function getLableTagAttr($value)
    {
        
        if($value){
            $value = json_decode($value, true);
            $tagNames = ProductTags::where('id', 'in', $value)->column('name');
            $value = $tagNames?:[];
        }
        return $value;
    }

    public function getMarkIconAttr($value)
    {
        return env('IMAGE_URL').$value;
    }

    public function getMiniIconAttr($value)
    {
        return env('IMAGE_URL').$value;
    }

    public function getMiniQrImgAttr($value)
    {
        return env('IMAGE_URL').$value;
    }

    public function getProductName($productId)
    {
        $product = $this->where('id', $productId)->with(['description'=>function($query){
            $query->field('name');
        }])->field('id')->find();
        return $product->description->name?:'';
    }

    public function batchGetProductName($productIds)
    {
        $productNames = $this->where('id', 'in', $productIds)->with(['description'=>function($query){
            $query->field('name');
        }])->column('description.name','id');
        return $productNames?:[];
    }


    public function batchGetProductInfo($productIds)
    {
        $productInfo = $this->alias('p')
            ->leftJoin('product_descriptions pd', 'p.id = pd.product_id')
            ->leftJoin('product_skus ps', 'p.id = ps.product_id')
            ->where('p.id', 'in', $productIds)
            ->where('pd.locale', 'zh_cn')
            ->where('ps.is_default', 1)
            ->field('p.id,p.images, pd.name, ps.price')
            ->select()
            ->toArray();
        foreach($productInfo as $key => $item){
            $productInfo[$key]['image'] = env('IMAGE_URL').$item['images'][0];
        }
        return $productInfo;
    }
}
